<template>
    <div class="payment-create">
        <el-card>
            <template #header>
                <div class="card-header">
                    <span>创建支付订单</span>
                </div>
            </template>
            
            <div v-if="loading" class="loading-container">
                <el-skeleton :rows="5" animated />
            </div>
            
            <div v-else-if="error" class="error-container">
                <el-alert
                    :title="error"
                    type="error"
                    show-icon
                    :closable="false"
                />
                <div class="mt-3 text-center">
                    <el-button type="primary" @click="goBack">返回</el-button>
                </div>
            </div>
            
            <div v-else-if="order" class="order-details">
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="订单编号">{{ order.orderNo }}</el-descriptions-item>
                    <el-descriptions-item label="课程名称">{{ order.tutoringTitle || '暂无课程名称' }}</el-descriptions-item>
                    <el-descriptions-item label="教师姓名">{{ order.teacherName || '暂无教师姓名' }}</el-descriptions-item>
                    <el-descriptions-item label="支付金额">¥{{ order.amount }}</el-descriptions-item>
                    <el-descriptions-item label="支付状态">
                        <el-tag :type="getStatusType(order.status)">
                            {{ getStatusText(order.status) }}
                        </el-tag>
                    </el-descriptions-item>
                </el-descriptions>
                
                <!-- 添加调试信息，实际部署前可删除 -->
                <div v-if="!order.tutoringTitle || !order.teacherName" class="debug-info mt-3">
                    <el-alert
                        title="课程或教师信息不完整"
                        type="warning"
                        :closable="false"
                    >
                        <p>原始订单数据:</p>
                        <pre>{{ JSON.stringify(order, null, 2) }}</pre>
                    </el-alert>
                </div>
                
                <div v-if="order.status === 0" class="payment-actions mt-3">
                    <el-button type="primary" @click="goToAlipay">支付宝支付</el-button>
                    <el-button @click="goBack">取消</el-button>
                </div>
                
                <div v-else class="mt-3 text-center">
                    <el-button type="primary" @click="goBack">返回</el-button>
                </div>
            </div>
        </el-card>
        
        <!-- 支付宝表单容器 -->
        <div v-html="alipayForm" ref="alipayFormContainer" style="display: none;"></div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { paymentService } from '@/api/payment'

// 全局暴露JSON对象，以便在模板中使用
const JSON = window.JSON

const router = useRouter()
const loading = ref(true)
const error = ref(null)
const order = ref(null)
const alipayForm = ref('')
const alipayFormContainer = ref(null)

// 获取支付状态类型
const getStatusType = (status) => {
    switch (status) {
        case 0: return 'warning'  // 未支付
        case 1: return 'success'  // 支付成功
        case 2: return 'danger'   // 支付失败
        default: return 'info'
    }
}

// 获取支付状态文本
const getStatusText = (status) => {
    switch (status) {
        case 0: return '未支付'
        case 1: return '支付成功'
        case 2: return '支付失败'
        default: return '未知状态'
    }
}

// 创建支付订单
const createPayment = async (bookingId) => {
    loading.value = true
    try {
        const response = await paymentService.createPayment(bookingId)
        order.value = response.data
    } catch (e) {
        error.value = e.response?.data?.message || '创建支付订单失败'
    } finally {
        loading.value = false
    }
}

// 跳转到支付宝支付
const goToAlipay = async () => {
    if (!order.value || !order.value.orderNo) {
        ElMessage.error('无效的订单信息')
        return
    }
    
    try {
        // 保存订单号到本地存储，方便支付结果页面获取
        localStorage.setItem('lastPaymentOrderNo', order.value.orderNo)
        console.log('保存订单号到本地存储:', order.value.orderNo)
        
        const response = await paymentService.getAlipayForm(order.value.orderNo)
        alipayForm.value = response.data
        
        // 等待DOM更新
        setTimeout(() => {
            // 自动提交表单
            const formElement = alipayFormContainer.value.querySelector('form')
            if (formElement) {
                formElement.submit()
            } else {
                ElMessage.error('获取支付表单失败')
            }
        }, 100)
    } catch (e) {
        ElMessage.error(e.response?.data?.message || '获取支付表单失败')
    }
}

// 返回上一页
const goBack = () => {
    router.go(-1)
}

onMounted(() => {
    // 优先从URL参数中获取orderNo
    const queryParams = new URLSearchParams(window.location.search);
    const orderNo = queryParams.get('orderNo');
    
    if (orderNo) {
        // 直接查询订单状态
        getPaymentStatus(orderNo);
        return;
    }
    
    // 尝试从本地存储中获取scheduleId或bookingId
    const scheduleId = localStorage.getItem('paymentScheduleId');
    const bookingId = localStorage.getItem('paymentBookingId');
    
    if (scheduleId) {
        // 使用课程安排ID创建支付订单
        createPaymentByScheduleId(scheduleId);
        // 清除本地存储
        localStorage.removeItem('paymentScheduleId');
    } else if (bookingId) {
        // 使用预约ID创建支付订单
        createPayment(bookingId);
        // 清除本地存储
        localStorage.removeItem('paymentBookingId');
    } else {
        error.value = '无效的预约信息，请重新选择课程进行支付';
        loading.value = false;
    }
})

// 查询订单状态
const getPaymentStatus = async (orderNo) => {
    loading.value = true;
    try {
        console.log('获取订单状态，订单号:', orderNo);
        const response = await paymentService.getPaymentStatus(orderNo);
        order.value = response.data;
        console.log('获取到订单详情:', order.value);
        
        // 如果缺少课程或教师信息，尝试再次请求
        if (!order.value.tutoringTitle || !order.value.teacherName) {
            console.log('订单缺少课程或教师信息，等待1秒后重试');
            
            // 等待1秒后再次请求订单信息
            setTimeout(async () => {
                try {
                    console.log('重新获取订单详情...');
                    const retryResponse = await paymentService.getPaymentStatus(orderNo);
                    if (retryResponse.data) {
                        order.value = retryResponse.data;
                        console.log('重新获取的订单详情:', order.value);
                    }
                } catch (retryError) {
                    console.error('重新获取订单详情失败:', retryError);
                }
            }, 1000);
        }
    } catch (e) {
        console.error('获取订单信息失败:', e);
        error.value = e.response?.data?.message || '获取订单信息失败';
    } finally {
        loading.value = false;
    }
}

// 创建支付订单（通过课程安排ID）
const createPaymentByScheduleId = async (scheduleId) => {
    loading.value = true;
    try {
        const response = await paymentService.createPaymentByScheduleId(scheduleId);
        order.value = response.data;
    } catch (e) {
        error.value = e.response?.data?.message || '创建支付订单失败';
    } finally {
        loading.value = false;
    }
}
</script>

<style scoped>
.payment-create {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.loading-container, .error-container {
    padding: 20px;
}

.order-details {
    max-width: 600px;
    margin: 0 auto;
}

.mt-3 {
    margin-top: 15px;
}

.text-center {
    text-align: center;
}

.payment-actions {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-top: 20px;
}
</style> 